import { initRederCamera } from "./init.js";

export function createGame() {
  const { camera, renderer } = initRederCamera();
  let current = null;
  let preKey = null;
  let timer = null;
  const map = {};

  const registry = (key, fn) => {
    map[key] = fn;
  };

  const unRegistry = (key, fn) => {
    map[key] = fn;
  };

  function animate() {
    timer = requestAnimationFrame(animate);
    if (!current) {
      return;
    }
    const { scene, update } = current;
    update?.();
    scene && renderer.render(scene, camera);
  }

  function stop() {
    cancelAnimationFrame(timer);
  }

  const start = (key) => {
    changeScene(key);
    animate();
  };

  const changeScene = (key) => {
    preKey = key;
    let preData = null;
    if (current) {
      const { destroy } = current;
      preData = destroy?.();
    }
    const Scene = map[key];

    if (Scene) {
      current = Scene({
        preData,
        preKey,

        changeScene,
        registry,
        unRegistry,
        start,
        stop,

        camera,
        renderer,
      });
    }
  };

  return {
    registry,
    unRegistry,
    start,
    stop,
    changeScene,
  };
}
